﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button v-if="hasPerm('SO_SOMain.Add')" type="primary" icon="plus" @click="handleAdd()">新建</a-button>
      <a-button
        v-if="hasPerm('SO_SOMain.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
      >删除</a-button>
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select v-model="queryParam.condition">
                <a-select-option key="cSOCode">销售订单号</a-select-option>
                <a-select-option key="cCusName">客户名称</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input allowClear @keydown="inputKeyDown" v-model="queryParam.keyword" placeholder="关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="() => {this.pagination.current = 1; this.getDataList()}">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :scroll="{ y: tableHight }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'checkbox' }"
      :bordered="true"
      size="small"
      :customRow="loadRow">
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime,'YYYY-MM-DD HH:mm') }}</span>

      <template slot="TotalNum" slot-scope="text">
        <span>{{ text.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</span>
      </template>
      <template slot="TotalAmount" slot-scope="text">
        <span>{{ text.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</span>
      </template>
      <span slot="UpdateState" slot-scope="text, record">
        <a-tag v-if="record.UpdateState == 0 && (record.UpdateMessage ===''||record.UpdateMessage ===null||record.UpdateMessage ===undefined)" color="red">未传</a-tag>
        <a-tag v-if="record.UpdateState == 0 && record.UpdateMessage !=='' && record.UpdateMessage ===null&&record.UpdateMessage ===undefined" color="red">已传失败</a-tag>
        <a-tag v-else-if="record.UpdateState == 1" color="green">已传成功</a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('SO_SOMain.Edit')&& record.State===0" @click.stop="handleEdit(record.Id)">编辑</a>
          <a-divider v-if="hasPerm('SO_SOMain.Edit')&&hasPerm('SO_SOMain.Delete')&& record.State===0" type="vertical" />
          <a v-if="hasPerm('SO_SOMain.Delete')&& record.State===0" @click.stop="handleDelete([record.Id])">删除</a>
          <a-divider v-if="hasPerm('SO_SOMain.Auditing')&&hasPerm('SO_SOMain.Delete') && record.State===0 " type="vertical" />
          <a v-if="hasPerm('SO_SOMain.Auditing')&& record.State===0" @click.stop="handleAuditing([record.Id])">审核</a>
          <a v-if=" record.State!==0" @click.stop="handleView(record.Id)">查看</a>
          <a-divider v-if="hasPerm('SO_SOMain.Change') && record.State===1 " type="vertical" />
          <a v-if=" record.State!==0" @click.stop="handleChange(record.Id)">变更</a>
          <a-divider type="vertical" />
          <a @click.stop="download(record.Id)">下载</a>
          <a-divider v-if=" record.HistoryCount>0" type="vertical" />
          <a v-if=" record.HistoryCount>0" @click.stop="ViewList(record.Id)">变更列表</a>
        </template>
      </span>
    </a-table>
    <edit-form ref="editForm" :parentObj="{...this}" :deptId="DeptId" @returnMain="handleReturnMain"></edit-form>
    <view-list ref="viewList"></view-list>
  </a-card>
</template>

<script>
import { mapState } from 'vuex'
import EditForm from './EditForm'
import ViewList from '../So_SoMain_History/List'
const columns = [
  { title: '销售订单号', dataIndex: 'cSOCode', width: '10%' },
  {
    title: '单据日期',
    dataIndex: 'dDate',
    align: 'center',
    customRender: (value, row) => {
      return row.dDate.substring(0, 10)
    },
    width: '10%'
  },
  { title: '客户编码', dataIndex: 'cCusCode', width: '10%' },
  { title: '客户名称', dataIndex: 'cCusName', width: '20%' },
  { title: '销售类型', dataIndex: 'cSTName', align: 'center', width: '8%' },
  { title: '总数量', dataIndex: 'TotalNum', align: 'center', width: '10%', scopedSlots: { customRender: 'TotalNum' } },
  { title: '总金额', dataIndex: 'TotalAmount', align: 'center', width: '10%', scopedSlots: { customRender: 'TotalAmount' } },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '140px' }
]

export default {
  components: {
    EditForm,
    ViewList
  },
  computed: {
    ...mapState({
      DeptId: state => state.app.DeptId
    })
  },
  watch: {
    DeptId: {
      handler (n, o) {
        this.$nextTick(() => {
          // 页面渲染完成后的回调
          this.tableHight = this.getTableHeight(true)
        })
        this.getDataList()
      },
      immediate: true
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHight = this.getTableHeight(true) + 24.5
    })
    this.getDataList()
  },
  data () {
    return {
      tableHight: 570, // 表格高度
      data: [],
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      loading: false,
      columns,
      queryParam: {},
      selectedRows: [],
      selectedRowKeys: []
    }
  },
  methods: {
    reset () {
      this.queryParam = {}
      this.pagination.current = 1
      this.pagination.pageSize = 20
      this.getDataList()
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/OrderManagement/SO_SOMain/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order || 'desc',
          DeptId: this.DeptId,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    download (id) {
      this.$http
        .post('/OrderManagement/SO_SOMain/PrintData', { id: id }, { responseType: 'blob' })
        .then((res) => {
          const url = URL.createObjectURL(res)
          console.log(url)
          const fileName = '销售合同'
          const aTag = document.createElement('a')
          aTag.download = fileName
          aTag.href = url
          aTag.click()
          URL.revokeObjectURL(aTag.href)
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    inputKeyDown (e) {
      if (e.keyCode === 13) {
        if (!this.queryParam[0].keyword) return this.$message.error('请输入查询条件')
        this.getDataList()
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleAdd () {
      this.$refs.editForm.openForm(null, '新建销售订单主表信息', false)
    },
    handleEdit (id) {
      this.$refs.editForm.openForm(id, '编辑销售订单主表信息', false)
    },
    handleView (id) {
      this.$refs.editForm.openForm(id, '编辑销售订单主表信息', true)
    },
    handleChange (id) {
      this.$refs.editForm.openForm(id, '变更销售订单主表信息', false)
    },
    ViewList (id) {
      this.$refs.viewList.openForm(id, '销售订单变更历史')
    },
    handleDelete (ids) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          this.$http.post('/OrderManagement/SO_SOMain/DeleteData', ids).then(resJson => {
            resolve()

            if (resJson.Success) {
              this.$message.success('操作成功!')

              this.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        }).catch(() => console.log('Oops errors!'))
      })
    },
    handleAuditing (ids) {
      this.$confirm('确认审核吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          this.$http.post('/OrderManagement/SO_SOMain/AuditingData', ids).then(resJson => {
            resolve()

            if (resJson.Success) {
              this.$message.success('操作成功!')

              this.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        }).catch(() => console.log('Oops errors!'))
      })
    },
    handleReturnMain () {
      this.getDataList()
    },
    // 表格点击选中取消
    loadRow (record, index) {
      return {
        on: {
          click: () => {
            if (record.disabled) return
            const key = record.Id
            if (this.selectedRowKeys.includes(key)) {
              const index = this.selectedRowKeys.findIndex(skey => skey === key)
              this.selectedRowKeys.splice(index, 1)
              this.selectedRows.splice(index, 1)
            } else {
              this.selectedRowKeys.push(key)
              this.selectedRows.push(record)
            }
          }
        }
      }
    },
    // 更新选中操作
    updateSelect (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    }
  }
}
</script>
